﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dycox.Collections;

namespace Dycox.Workflows
{
    public class StageEventProcessorCollection : OwnedCollection<StageEventProcessor, Stage>
    {
        internal StageEventProcessorCollection(Stage stage, EventScenario scenario)
            : base(stage)
        {
            _scenario = scenario;
        }

        private EventScenario _scenario;

        public EventScenario Scenario
        {
            get { return _scenario; }
        }


        protected override void SetItemOwner(StageEventProcessor item, Stage parent)
        {
            if (!item.IsScenarioSupported(_scenario))
                throw new NotSupportedException("The specified processor does not support " + _scenario);

            if (item.Exclusive && this.Any(o => o.GetType() == item.GetType()))
                throw new WorkflowException("Processor " + item.GetType() + " is already existed exclusivly.");

            item.Stage = parent;
        }

        protected override Stage GetItemOwner(StageEventProcessor item)
        {
            return item.Stage;
        }

        public T GetProcessor<T>()
            where T : StageEventProcessor
        {
            Type type = typeof(T);
            var array = this.Where(o => o.GetType() == type).ToArray();

            if (array.Length == 0)
                return null;
            else
                return (T)array[0];
        }


        internal void Process(WFStep step)
        {
            foreach (var p in this)
            {
                p.Process(step, _scenario);
            }
        }

    }
}
